package com.example.androidjsonparsingdemo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {
	private Context context;
	String url = "http://192.168.0.75/quiz/test.php";
	TextView QuesTV = null;
	TextView Opt1TV = null;
	TextView Opt2TV = null;
	TextView Opt3TV = null;
	TextView Opt4TV = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		new ProgressTask(MainActivity.this).execute();
	}
	

	private class ProgressTask extends AsyncTask<String, Void, Boolean> {
		
		private ProgressDialog dialog;
		Activity activity;

		// private List<Message> messages;
		public ProgressTask(Activity activity) {
			this.activity = activity;
			context = activity;
			dialog = new ProgressDialog(context);
		}

		private Context context;

		protected void onPreExecute() {
			this.dialog.setMessage("Progress start");
			this.dialog.show();
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
		}

		protected Boolean doInBackground(final String... args) {

			JSONParser jParser = new JSONParser();
			JSONArray jArr = jParser.getJSONFromUrl(url);
			Questions ques=null;
			QuesTV = (TextView) findViewById(R.id.questionTextView);
			Opt1TV = (TextView) findViewById(R.id.Option1TextView);
			Opt2TV = (TextView) findViewById(R.id.Option2TextView);
			Opt3TV = (TextView) findViewById(R.id.Option3TextView);
			Opt4TV = (TextView) findViewById(R.id.Option4TextView);

			for (int i = 0; i < jArr.length(); i++) {
				try {
					JSONObject jObj = jArr.getJSONObject(i);
					ques.setQ_id(jObj.getInt("q_id"));
					ques.setQuestion(jObj.getString("question"));
					ques.setOption1(jObj.getString("option1"));
					ques.setOption2(jObj.getString("option2"));
					ques.setOption3(jObj.getString("option3"));
					ques.setOption4(jObj.getString("option4"));
					ques.setAnswer(jObj.getString("answer"));
					String user_ids = jObj.getString("user_ids");

					QuesTV.setText(ques.getQuestion());
					Opt1TV.setText(ques.getOption1());
					Opt2TV.setText(ques.getOption2());
					Opt3TV.setText(ques.getOption3());
					Opt4TV.setText(ques.getOption4());
					
					

				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			return null;
		}

	}
}